package xyz.xtt.user.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import xyz.xtt.common.response.ApiResult;
import xyz.xtt.user.entity.TblUserDeliveryAddress;
import xyz.xtt.user.mapper.TblUserDeliveryAddressMapper;
import xyz.xtt.user.request.UserAddressRequest;
import xyz.xtt.user.service.ITblUserDeliveryAddressService;

/**
 * <p>
 * 用户地址信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-17
 */
@Service
public class TblUserDeliveryAddressServiceImpl extends ServiceImpl<TblUserDeliveryAddressMapper, TblUserDeliveryAddress>
		implements ITblUserDeliveryAddressService {

	@Autowired
	private TblUserDeliveryAddressMapper tblUserDeliveryAddressMapper;

	@Override
	public void addAddress(TblUserDeliveryAddress tblUserDeliveryAddress) {
		tblUserDeliveryAddressMapper.insert(tblUserDeliveryAddress);
	}

	@Override
	public void deleteAddress(Long id) {
		tblUserDeliveryAddressMapper.deleteById(id);
	}

	@Override
	public void updateAddress(TblUserDeliveryAddress tblUserDeliveryAddress) {
		tblUserDeliveryAddressMapper.updateById(tblUserDeliveryAddress);
	}

	@Override
	public List<TblUserDeliveryAddress> getAddress(Long userId) {
		// 通过用户id查询
		LambdaQueryWrapper<TblUserDeliveryAddress> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TblUserDeliveryAddress::getUserId, userId).orderByDesc(TblUserDeliveryAddress::getIsDefault);
		return tblUserDeliveryAddressMapper.selectList(queryWrapper);
	}

	@Override
	public List<TblUserDeliveryAddress> getUserAddress(String uid) {
		return this.getAddress(Long.valueOf(uid));
	}

	@Override
	public ApiResult<String> addUserAddress(String uid, UserAddressRequest userAddress) {
		TblUserDeliveryAddress tblUserDeliveryAddress = new TblUserDeliveryAddress();
		tblUserDeliveryAddress.setId(IdWorker.getIdStr());
		tblUserDeliveryAddress.setUserId(uid);
		tblUserDeliveryAddress.setDeliveryAddress(userAddress.getAddress());
		tblUserDeliveryAddress.setUserName(userAddress.getUserName());
		tblUserDeliveryAddress.setPhone(userAddress.getPhone());
		tblUserDeliveryAddress.setLastModifyDate(LocalDateTime.now());
		tblUserDeliveryAddress.setDeliveryArea(userAddress.getArea());
		boolean save = this.save(tblUserDeliveryAddress);
		return save ? ApiResult.ok(tblUserDeliveryAddress.getId()) : ApiResult.failure();
	}

}
